package com.fingard.dsp.bank.directbank.cgb02;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptData;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptDataHelper;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directConfig.ReceiptProConfig;
import com.fingard.dsp.bank.directbank.bankInterface.IReceiptPro;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.dsp.bank.sepro.ReceiptPro;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;
import com.fingard.FGBiz;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

/**
 * @Description TODO
 * @Author xtt
 **/
public class CGB02ReceiptPro extends CGB02Base implements IReceiptPro {

    @Override
    public RetAtsReceipt qryReceiptOneDay(ReceiptProConfig pConfig, ReqQryReceipt pReqReceipt, Date pOneDay) throws Exception {
        //从前置机sftp上下载前一日的电子回单
        String downType = getBankConfig().getValueAsString("receiptRequestType");

        String downType2 = bankFront.getStrValueByFor("receiptDownloadType", "");
        if(StringHelper.hasAnyChar(downType2)){
            downType = downType2;//前置机的配置覆盖config
        }
        String qryDay8 = Format.Date8Format.format(pOneDay);
        ReceiptDataHelper receiptHelper = new ReceiptDataHelper(pReqReceipt.reqHeader.tenant, pOneDay);

        //过渡路径
        String saveDirPathTemp = pConfig.getSaveSubDir(pReqReceipt.reqHeader, pOneDay) + File.separator + qryDay8 + File.separator + ReceiptPro.getTransID();

        return downlaodForSftpAndInsert(pReqReceipt,receiptHelper,saveDirPathTemp,qryDay8);
    }

    /**
     * sftp方式回单获取
     *
     * @param p_reqReceipt
     * @return
     */
    public RetAtsReceipt downlaodForSftpAndInsert(ReqQryReceipt p_reqReceipt, ReceiptDataHelper receiptHelper, String saveDirPathTemp, String qryDay8) throws IOException {
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);

        SftpPortClient sftpPortClient = null;

        try {
                FtpSet ftpSet = bankFront.getFtpSet("receipt");
                ftpSet.downDir = StringHelper.trimEnd(ftpSet.downDir, "/") + "/";
                WriteBankLogLn("SFTP下载地址" + ftpSet.serverIP + ":" + ftpSet.port);
                WriteBankLogLn("开始遍历服务器文件目录" + ftpSet.downDir + qryDay8);

                sftpPortClient = new SftpPortClient(ftpSet);
                ArrayList<String> ftpFileList = sftpPortClient.listNames(ftpSet.downDir + qryDay8);
                if (ftpFileList.size() == 1) {
                    WriteBankLogLn("当前日期："+qryDay8+"无回单文件");
                    retAts.respCode = "0";
                    retAts.respInfo = "今日无回单文件";
                    return retAts;
                }

                FtpReceiver ftpReceiver = sftpPortClient.downloadFile(ftpSet.downDir + qryDay8,saveDirPathTemp);
                File tmpFile = new File(saveDirPathTemp) ;
                File[] files = tmpFile.listFiles();
            int[] retVals = new int[3];
            retVals[0] = 0;//总pdf个数
            retVals[1] = 0;//新增
            retVals[2] = 0;//已存在
                for (File file : files) {
                    String ftpFileName = file.getName();
                    if (ftpFileName.contains(".txt")) {
                        WriteBankLogLn("解析汇总文件:" + ftpFileName);
                        //保存路径
                        if (ftpReceiver.isCompleted) {
                            retAts.respCode = "0";

                            //解析汇总文件返回map
                            String[] line = FileHelper.readFileText(saveDirPathTemp,"UTF-8").split("\n|\r");
                            int totalFiles = 0;
                                //读取文件内容
                                    for (String pfiles : line) {
                                        if(!pfiles.contains("\\|")){
                                            totalFiles = Integer.valueOf(pfiles);
                                        }else{
                                            //推送共享文件夹
//入库
                                            String[] receiptInfo = pfiles.split("\\|");
                                            ReceiptData eachData = new ReceiptData();
                                            eachData.bank = "";
                                            eachData.srcSys = "CGB02";
                                            eachData.localFile = saveDirPathTemp + File.separator+receiptInfo[1]+".pdf";
                                            eachData.receiptNo = receiptInfo[1];
                                            eachData.busDate = Integer.parseInt(qryDay8);
                                            eachData.bnkSeqNo = receiptInfo[1] + receiptInfo[0]+qryDay8;
                                            if(receiptInfo[4].contains("D")){
                                                eachData.moneyWay = "1";
                                            }else if(receiptInfo[4].contains("C")){
                                                eachData.moneyWay = "2";
                                            }
                                            eachData.downState = "2";
                                            eachData.downTime = new Date();
                                            int inRe = receiptHelper.insertIfNotExist(eachData, true);
                                            if(inRe>0){
                                                retVals[1] = retVals[1] + 1;
                                            }else if(inRe == 0){
                                                retVals[2] = retVals[2] + 1;
                                            }
                                            WriteBankLogLn(eachData.receiptNo+"写入数据库，影响行数："+inRe);
                                        }
                                    }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = ftpFileName + "回单文件下载失败:" + ftpReceiver.connMsg + "+" + ftpReceiver.connState;
                            WriteBankLogLn(ftpFileName + "回单文件下载失败:" + ftpReceiver.connMsg + "+" + ftpReceiver.connState);
                        }
                    }
                }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        } finally {
            if (sftpPortClient != null) {
                sftpPortClient.disconnect();
            }
        }

        return retAts;
    }

}
